<template>
  <el-card class="property-match-card">
    <template #header>
      <div class="card-header">
        <span>🏠 智能匹配房源 ({{ matchData?.total_matched || 0 }})</span>
        <el-button
          type="primary"
          size="small"
          :loading="loading"
          @click="loadMatches"
        >
          <el-icon><Refresh /></el-icon>
          刷新匹配
        </el-button>
      </div>
    </template>

    <el-skeleton
      :loading="loading"
      :rows="3"
      animated
    >
      <div v-if="matchData && matchData.matches.length > 0">
        <!-- 匹配参数控制 -->
        <div class="match-controls">
          <el-space wrap>
            <el-text size="small">
              匹配参数:
            </el-text>
            <el-input-number
              v-model="topN"
              :min="1"
              :max="50"
              size="small"
              placeholder="数量"
              @change="loadMatches"
            />
            <el-text size="small">
              个,最低分数:
            </el-text>
            <el-input-number
              v-model="minScore"
              :min="0"
              :max="100"
              size="small"
              placeholder="分数"
              @change="loadMatches"
            />
            <el-checkbox
              v-model="includeUnavailable"
              size="small"
              @change="loadMatches"
            >
              包含已租房源
            </el-checkbox>
          </el-space>
        </div>

        <el-divider />

        <!-- 匹配结果表格 -->
        <el-table
          :data="matchData.matches"
          stripe
          border
        >
          <el-table-column
            label="匹配度"
            width="150"
            fixed
          >
            <template #default="{ row }">
              <el-progress
                :percentage="Math.round(row.match_score)"
                :color="getScoreColor(row.match_score)"
                :stroke-width="20"
              >
                <span class="score-text">{{ row.match_score.toFixed(1) }}分</span>
              </el-progress>
            </template>
          </el-table-column>

          <el-table-column
            label="房源信息"
            min-width="250"
          >
            <template #default="{ row }">
              <div class="property-info">
                <div class="property-name">
                  <el-icon><House /></el-icon>
                  {{ row.property.community_name }}
                </div>
                <div class="property-details">
                  {{ row.property.layout }} | {{ row.property.area }}㎡ | {{ row.property.orientation || '未知朝向' }}
                </div>
                <div class="property-address">
                  <el-icon><Location /></el-icon>
                  <el-text
                    size="small"
                    type="info"
                  >
                    {{ row.property.address }}
                  </el-text>
                </div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="租金"
            width="120"
          >
            <template #default="{ row }">
              <div class="price">
                <el-text
                  type="danger"
                  size="large"
                  tag="b"
                >
                  {{ row.property.rent_price }}
                </el-text>
                <el-text size="small">
                  元/月
                </el-text>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="匹配理由"
            min-width="300"
          >
            <template #default="{ row }">
              <div class="match-reasons">
                <el-tag
                  v-for="(reason, idx) in row.match_reasons"
                  :key="idx"
                  size="small"
                  type="success"
                  effect="light"
                  class="reason-tag"
                >
                  {{ reason }}
                </el-tag>
                <el-tag
                  v-for="(insight, idx) in row.ai_insights"
                  :key="`insight-${idx}`"
                  size="small"
                  type="primary"
                  effect="light"
                  class="reason-tag"
                >
                  {{ insight }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            label="分数明细"
            width="150"
          >
            <template #default="{ row }">
              <el-popover
                placement="left"
                :width="300"
                trigger="hover"
              >
                <template #reference>
                  <el-button
                    link
                    type="primary"
                  >
                    <el-icon><DataAnalysis /></el-icon>
                    查看详情
                  </el-button>
                </template>
                <div class="score-breakdown">
                  <h4>匹配分数明细</h4>
                  <el-divider />
                  <div class="score-item">
                    <span>💰 预算匹配:</span>
                    <el-progress
                      :percentage="row.score_breakdown.budget_score"
                      :stroke-width="10"
                      :show-text="true"
                    />
                  </div>
                  <div class="score-item">
                    <span>🏠 户型匹配:</span>
                    <el-progress
                      :percentage="row.score_breakdown.layout_score"
                      :stroke-width="10"
                    />
                  </div>
                  <div class="score-item">
                    <span>📍 区域匹配:</span>
                    <el-progress
                      :percentage="row.score_breakdown.area_score"
                      :stroke-width="10"
                    />
                  </div>
                  <div class="score-item">
                    <span>✅ 标签匹配:</span>
                    <el-progress
                      :percentage="row.score_breakdown.tag_score"
                      :stroke-width="10"
                    />
                  </div>
                  <div
                    v-if="row.score_breakdown.commute_score > 0"
                    class="score-item"
                  >
                    <span>🚇 通勤匹配:</span>
                    <el-progress
                      :percentage="row.score_breakdown.commute_score"
                      :stroke-width="10"
                    />
                  </div>
                  <el-divider />
                  <div class="total-score">
                    <span>综合得分:</span>
                    <el-text
                      type="primary"
                      size="large"
                      tag="b"
                    >
                      {{ row.score_breakdown.total_score.toFixed(1) }}/100
                    </el-text>
                  </div>
                </div>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            width="180"
            fixed="right"
          >
            <template #default="{ row }">
              <el-button-group>
                <el-button
                  size="small"
                  @click="viewProperty(row.property_id)"
                >
                  <el-icon><View /></el-icon>
                  查看
                </el-button>
                <el-button
                  size="small"
                  type="primary"
                  @click="scheduleViewing(row.property_id)"
                >
                  <el-icon><Calendar /></el-icon>
                  安排带看
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>

        <!-- 计算时间 -->
        <div class="footer-info">
          <el-text
            size="small"
            type="info"
          >
            <el-icon><Clock /></el-icon>
            计算时间: {{ formatTime(matchData.computed_at) }}
          </el-text>
        </div>
      </div>

      <el-empty
        v-else
        description="暂无匹配房源"
        :image-size="120"
      >
        <el-button
          type="primary"
          @click="loadMatches"
        >
          <el-icon><Refresh /></el-icon>
          重新匹配
        </el-button>
      </el-empty>
    </el-skeleton>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  House,
  Location,
  DataAnalysis,
  View,
  Calendar,
  Clock
} from '@element-plus/icons-vue'
import { leadApi } from '@/api'
import type { PropertyMatchListResponse } from '@/api/types'
import { formatDistanceToNow } from 'date-fns'
import { zhCN } from 'date-fns/locale'

interface Props {
  leadId: number
}

const props = defineProps<Props>()
const loading = ref(false)
const matchData = ref<PropertyMatchListResponse | null>(null)

// 匹配参数
const topN = ref(10)
const minScore = ref(50)
const includeUnavailable = ref(false)

const loadMatches = async () => {
  loading.value = true
  try {
    matchData.value = await leadApi.matchProperties(props.leadId, {
      top_n: topN.value,
      min_score: minScore.value,
      include_unavailable: includeUnavailable.value
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : '加载匹配房源失败'
    ElMessage.error(message)
  } finally {
    loading.value = false
  }
}

const getScoreColor = (score: number): string => {
  if (score >= 80) return '#67C23A'
  if (score >= 60) return '#E6A23C'
  return '#F56C6C'
}

const viewProperty = (propertyId: number) => {
  // TODO: 跳转到房源详情页
  window.open(`/properties/${propertyId}`, '_blank')
}

const scheduleViewing = (propertyId: number) => {
  // TODO: 打开带看安排弹窗
  ElMessage.info(`安排带看功能开发中 (房源ID: ${propertyId})`)
}

const formatTime = (timestamp: string): string => {
  try {
    return formatDistanceToNow(new Date(timestamp), {
      addSuffix: true,
      locale: zhCN
    })
  } catch {
    return timestamp
  }
}

onMounted(() => {
  loadMatches()
})
</script>

<style scoped lang="scss">
.property-match-card {
  margin-top: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: bold;
  }

  .match-controls {
    padding: 10px 0;
  }

  .property-info {
    .property-name {
      font-weight: bold;
      margin-bottom: 6px;
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .property-details {
      font-size: 13px;
      color: #666;
      margin-bottom: 4px;
    }

    .property-address {
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;
    }
  }

  .price {
    display: flex;
    flex-direction: column;
    align-items: center;
  }

  .match-reasons {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .reason-tag {
    margin: 0;
  }

  .score-text {
    font-size: 12px;
    font-weight: bold;
  }

  .score-breakdown {
    h4 {
      margin: 0 0 10px 0;
      font-size: 16px;
    }

    .score-item {
      margin: 12px 0;

      span {
        display: block;
        margin-bottom: 6px;
        font-size: 14px;
      }
    }

    .total-score {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
    }
  }

  .footer-info {
    margin-top: 16px;
    text-align: right;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 6px;
  }
}
</style>
